package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"nov3-exam/cache"
	"nov3-exam/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var book []models.Book
	redis_key := "book_list"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &book)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "列表获取成功",
		"data": book,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var book models.Book
	redis_key := "book_detail" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Table("books").
			Select(
				" books.id",
				"books.author",
				" books.name",
				"books.content",
				"comments.content",
				"users.username",
			).
			Joins("LEFT JOIN comments ON comments.bid = books.id").
			Joins("LEFT JOIN users ON comments.uid = users.id").
			Where("id = ?", id).Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &book)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "详情获取成功",
		"data": book,
	})
	return
}

func Comment(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	bid, _ := strconv.Atoi(c.Query("bid"))
	content := c.Query("content")
	data := models.Comment{
		Bid:     bid,
		Uid:     uid,
		Content: content,
	}
	models.DB.Create(&data)
	redis_key := "comment_add_" + strconv.Itoa(int(data.ID))
	cache.Rdb.Set(cache.Ctx, redis_key, data, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "评论成功",
	})
	return
}

func CommentList(c *gin.Context) {

}
